package cmd

import (
	ckeadm "ckeadm/cmd/apis"
	"ckeadm/cmd/runner"
	"ckeadm/constants"
	"encoding/base64"
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/urfave/cli"
	"os"
)

func UpgradeV4Command() cli.Command {
	var upgradeFlags = []cli.Flag {
		runner.PrivateKeyDefaultRootKey,
		runner.AnsibleConfigDirFlag,
		runner.AnsibleUpgradeImageFlag,
		runner.LogLevelFlag,
	}

	return cli.Command {
		Name:   "upgrade-v4",
		Usage:  "Upgrade Cke Cluster to V4",
		Action: runUpgradeV4,
		Flags:  upgradeFlags,
	}
}

// runKubeletStart executes kubelet start logic.
func runUpgradeV4(ctx *cli.Context) error {
	logrus.Infof("start upgrade cluster to v4")
	ansibleDir := ctx.String("config-dir")

	var privatekey string
	var err error
	if privatekey, err = runner.GetPrivateKeyFromFile(ctx.String("private-key")); err != nil {
		return fmt.Errorf("error while get connection private key %s, err: %s", ctx.String("private-key"), err.Error())
	}

	if info, err := os.Stat(ansibleDir); err != nil || !info.IsDir(){
		logrus.Errorf("dir path (%s) unexist or is not a dir, err (%v). check config patch again", ansibleDir, err)
		return fmt.Errorf("dir path (%s) unexist or is not a dir, err (%v). check config patch again", ansibleDir, err)
	}
	var invFile = fmt.Sprintf("%s/%s", ansibleDir, "my_inventory.cfg")
	var allFile = fmt.Sprintf("%s/group_vars/%s", ansibleDir, "all.yml")

	var ug = &ckeadm.AnsibleDockerPerms {
		ContainerName: fmt.Sprintf("%s-%s-%s", constants.CkeDeployContainerName, "upgrade-v4", base64.RawURLEncoding.EncodeToString([]byte(ansibleDir))),
		ImageName:     ctx.String("upgrade-image"),
		PrivateKey:    privatekey,
		InvFilePath:   invFile,
		AllFilePath:   allFile,
		ExecerPatch:   fmt.Sprintf("%s/%s", constants.CkeDeployDir, "ckev4-upgrade.yml"),
	}

	mounts := append([]string {
		fmt.Sprintf("%s:%s", ug.InvFilePath, constants.AnsibleConfig),
		fmt.Sprintf("%s:%s", ug.AllFilePath, constants.AnsibleAllConfig),
	})

	return runner.AnsibleRunner(ug.ContainerName, ug.ImageName, ug.ExecerPatch, false, ug.PrivateKey, constants.AnsibleLogLevel, mounts...)
}